import { Context } from 'koa';
import pool from '../config/database';
import { calculateY, calculateOff } from '../utils/calculator';

// Define the request body interface
interface CalculationRequest {
    product_id: string;
    profit_value: number;
    profit_type: 'fixed' | 'cost' | 'price';
    cost: number;
    coupon: number;
    off: number;
    y: number;
    weight: number;
    withdrawal_fee_rate: number;
    platform_commission_rate: number;
    sfp_fee_rate: number;
    talent_commission_rate: number;
    transaction_fee_rate: number;
    vat_rate: number;
    bonus_cashback_rate: number;
    logistics_cost_per_10g: number;
    exchange_rate: number;
    buyer_shipping_fee: number;
    type: 'pricing' | 'adjustment';
}

export const saveCalculation = async (ctx: Context) => {
    try {
        const requestBody = ctx.request.body as CalculationRequest & { created_at: string };
        const {
            product_id,
            profit_value,
            profit_type,
            cost,
            coupon,
            off,
            y,
            weight,
            withdrawal_fee_rate,
            platform_commission_rate,
            sfp_fee_rate,
            talent_commission_rate,
            transaction_fee_rate,
            vat_rate,
            bonus_cashback_rate,
            logistics_cost_per_10g,
            exchange_rate,
            buyer_shipping_fee,
            type,
            created_at
        } = requestBody;

        // Calculate the result using calculateY function
        const result = calculateY(
            Number(profit_value),
            profit_type,
            Number(cost),
            Number(coupon),
            Number(off),
            Number(weight),
            Number(withdrawal_fee_rate),
            Number(platform_commission_rate),
            Number(sfp_fee_rate),
            Number(talent_commission_rate),
            Number(transaction_fee_rate),
            Number(vat_rate),
            Number(bonus_cashback_rate),
            Number(logistics_cost_per_10g),
            Number(exchange_rate),
            Number(buyer_shipping_fee)
        );

        // Save to database
        const [rows] = await pool.execute(
            `INSERT INTO calculations (
                product_id, profit_value, profit_type, cost, coupon, off, y, weight,
                withdrawal_fee_rate, platform_commission_rate, sfp_fee_rate,
                talent_commission_rate, transaction_fee_rate, vat_rate,
                bonus_cashback_rate, logistics_cost_per_10g, exchange_rate,
                buyer_shipping_fee, result, type, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
                product_id,
                profit_value,
                profit_type,
                cost,
                coupon,
                off,
                y,
                weight,
                withdrawal_fee_rate,
                platform_commission_rate,
                sfp_fee_rate,
                talent_commission_rate,
                transaction_fee_rate,
                vat_rate,
                bonus_cashback_rate,
                logistics_cost_per_10g,
                exchange_rate,
                buyer_shipping_fee,
                JSON.stringify(result),
                type,
                created_at
            ]
        );

        ctx.body = {
            success: true,
            data: {
                id: (rows as any).insertId,
                product_id,
                result
            }
        };
    } catch (error) {
        console.error('Error saving calculation:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            error: 'Failed to save calculation'
        };
    }
};

export const getCalculationsByProductId = async (ctx: Context) => {
    try {
        const { product_id } = ctx.params;
        
        const [rows] = await pool.execute(
            'SELECT * FROM calculations WHERE product_id = ? ORDER BY created_at DESC',
            [product_id]
        );

        ctx.body = {
            success: true,
            data: rows
        };
    } catch (error) {
        console.error('Error fetching calculations:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            error: 'Failed to fetch calculations'
        };
    }
};

export const getCalculationHistory = async (ctx: Context) => {
    try {
        const { type, product_id } = ctx.query;
        let query = 'SELECT * FROM calculations';
        const params = [];

        if (product_id) {
            query += ' WHERE product_id = ?';
            params.push(product_id);
        }

        if (type && type !== 'all') {
            if (product_id) {
                query += ' AND type = ?';
            } else {
                query += ' WHERE type = ?';
            }
            params.push(type);
        }

        query += ' ORDER BY created_at DESC LIMIT 100';

        const [rows] = await pool.execute(query, params);

        ctx.body = {
            success: true,
            data: rows
        };
    } catch (error) {
        console.error('Error fetching calculation history:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            error: 'Failed to fetch calculation history'
        };
    }
}; 